package cn.edu.xust.util.ruoyi;

import cn.edu.xust.entity.SysUserEntity;
import cn.edu.xust.service.SysUserService;
import cn.edu.xust.util.BeanContext;
import cn.edu.xust.util.JWTUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;

/**
 * shiro 工具类
 *
 * @author ruoyi
 */
public class ShiroUtils {

    public static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    public static Session getSession() {
        return SecurityUtils.getSubject().getSession();
    }

    public static void logout() {
        getSubject().logout();
    }

    public static SysUserEntity getSysUser() {
        SysUserEntity user = null;
        Object obj = getSubject().getPrincipal();
        if (StringUtils.isNotNull(obj)) {
            user = new SysUserEntity();
            String jwt = (String) obj;
            String rjwt = jwt.replace("Bearer ", "");
            String username = null;
            //decode时候出错，可能是token的长度和规定好的不一样了
            try {
                username = JWTUtil.getUsername(rjwt);
            } catch (Exception e) {
                throw new AuthenticationException("token非法，不是规范的token，可能被篡改了，或者过期了");
            }
            if (!JWTUtil.verify(rjwt) || username == null) {
                throw new AuthenticationException("token认证失效，token错误或者过期，重新登陆");
            }
            SysUserService sysUserService = BeanContext.getBean("sysUserService");
            user = sysUserService.getByName(username);
            if (user == null) {
                throw new AuthenticationException("该用户不存在");
            }
//            BeanUtils.copyBeanProp(user, obj);
        }
        return user;
    }

    public static void setSysUser(SysUserEntity user) {
        Subject subject = getSubject();
        PrincipalCollection principalCollection = subject.getPrincipals();
        String realmName = principalCollection.getRealmNames().iterator().next();
        PrincipalCollection newPrincipalCollection = new SimplePrincipalCollection(user, realmName);
        // 重新加载Principal
        subject.runAs(newPrincipalCollection);
    }

    public static Long getUserId() {
        return getSysUser().getUid().longValue();
    }

    public static String getLoginName() {
        return getSysUser().getNickname();
    }

    public static String getIp() {
        return StringUtils.substring(getSubject().getSession().getHost(), 0, 128);
    }

    public static String getSessionId() {
        return String.valueOf(getSubject().getSession().getId());
    }

    /**
     * 生成随机盐
     */
    public static String randomSalt() {
        // 一个Byte占两个字节，此处生成的3字节，字符串长度为6
        SecureRandomNumberGenerator secureRandom = new SecureRandomNumberGenerator();
        String hex = secureRandom.nextBytes(3).toHex();
        return hex;
    }
}
